// 在你的 WebSocket 模块中
import mitt from "mitt";

let url = "ws://127.0.0.1:8004/ws"; // 请求后端地址
const emitter = mitt();

const socket = {
  websocket: null,
  init() {
    socket.websocket = new WebSocket(url);
    socket.websocket.onmessage = (e) => {
      emitter.emit("websocketMessage", e.data); // 触发自定义事件
      console.log(e.data);
    };
    socket.websocket.onclose = (e) => {
      console.log(e);
    };
  },

  send(e) {
    if (socket.websocket.readyState === 0) {
      setTimeout(() => {
        socket.websocket.send(JSON.stringify(e));
      }, 1000);
    } else {
      socket.websocket.send(JSON.stringify(e));
    }
  },
};

export { socket, emitter };
